package com.my_musc_service.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * @Auther: yuansong
 * @Date: 2021/5/31 21:54
 * @Description:
 */
@Slf4j
@Order(-100)
@Component
@WebFilter(filterName = "printURLFilter", urlPatterns = {"/*"})
public class PrintURLFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestUrl = getRequestUrl(request);
        log.info(requestUrl);
//        System.out.println(stringBuilder.toString());
        doFilter(request, response, filterChain);
    }

    private String getRequestUrl(HttpServletRequest request) throws UnsupportedEncodingException {
        StringBuilder stringBuilder = new StringBuilder();
        request.setCharacterEncoding("UTF-8");
        StringBuffer requestURL = request.getRequestURL();
        stringBuilder.append(request.getMethod())
                .append(": ")
                .append(requestURL);
        String queryString = request.getQueryString();
        if (queryString != null) {
            String queryParam = URLDecoder.decode(queryString, "UTF-8");
            stringBuilder.append("?")
                    .append(queryParam);
        }
        return stringBuilder.toString();
    }
}

//        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Access-Control-Allow-Credentials", "true");
//        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
//        response.setHeader("Access-Control-Max-Age", "3600");
//        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me,token,auth-token,Origin");
//        response.setHeader("Access-Control-Request-Headers", "Origin, X-Requested-With, content-Type, Accept, Authorization,auth-token");

